Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Python Functions → Defining a Function

Python Functions

Defining a Function

Functions are reusable blocks of code that perform specific tasks. They enhance code readability, organization, and efficiency by preventing repetition and promoting modularity. Let's explore how to define and utilize functions in Python through various examples.

1. Defining a Simple Function

The basic structure of a Python function involves the `def` keyword, followed by the function name, parentheses `()`, and a colon `:`. The code block within the function is indented.
Defining function in Python def greet(name): # 'name' is a parameter print(f"Hello, {name}!") greet("Alice") # Calling the function with an argument greet("Bob")

Output

Hello, Alice! Hello, Bob!
Here, `greet` is the function name, `name` is a parameter (a variable accepting input), and `"Hello, {name}!"` is the function body. The `greet()` calls are examples of function invocation, passing "Alice" and "Bob" as arguments. The docstring (the string within triple quotes) is crucial for documentation.

2. Functions with Multiple Parameters and Return Values

Functions can accept multiple parameters and return values using the `return` statement.
Functions with Multiple Parameters and Return Values in python def add_numbers(x, y): """Adds two numbers and returns the sum.""" sum = x + y return sum def calculate_area(length, width): """Calculates and returns the area of a rectangle.""" area = length * width return area result = add_numbers(5, 3) print(f"The sum is: {result}") rectangle_area = calculate_area(10, 5) print(f"The area of the rectangle is: {rectangle_area}") def get_details(name, age, city="Unknown"): #city has a default value """Returns a dictionary containing personal details.""" return {"name": name, "age": age, "city": city} details = get_details("Charlie", 30, "New York") print(details) details2 = get_details("David", 25) #Using default value for city print(details2)

Output

The sum is: 8 The area of the rectangle is: 50 {'name': 'Charlie', 'age': 30, 'city': 'New York'} {'name': 'David', 'age': 25, 'city': 'Unknown'}
`add_numbers` returns the sum, while `calculate_area` returns the calculated area. Note the use of default parameter values in `get_details` for `city`.

3. Functions with No Return Value

Functions don't necessarily need a `return` statement. If omitted, they implicitly return `None`.
Python Functions with No Return Value def print_message(message): """Prints a message to the console.""" print(message) returned_value = print_message("This function doesn't return anything explicitly.") print(returned_value)

Output

This function doesn't return anything explicitly. None

4. Nested Functions (Closures)

Functions can be defined inside other functions, creating closures. Inner functions can access variables from their enclosing scope.
Python nested functions def outer_function(x): """Demonstrates a nested function (closure).""" y = 10 def inner_function(z): """Inner function accessing variables from outer scope.""" return x + y + z return inner_function my_closure = outer_function(5) # x is 5 here result = my_closure(3) # z is 3 here. y is accessed from the outer scope print(result)

Output

18
`inner_function` is a closure because it "closes over" the variables `x` and `y` from `outer_function`.

Tutorials